from web3 import Web3
from pymongo import MongoClient
from datetime import datetime
from decimal import Decimal
from bson.decimal128 import Decimal128
import os
client = MongoClient(os.getenv('db'))
db = client.eth
# w3 = Web3(Web3.HTTPProvider("https://mainnet.infura.io/v3/6e6a3c3e676b4ab1ad7a7126b70169e9"))
w3 = Web3(Web3.WebsocketProvider("ws://127.0.01:8555"))
# print(w3.eth.get_balance('0xd3CdA913deB6f67967B99D67aCDFa1712C293601'))
# print(w3.eth.block_number)
# print(w3.eth.gas_price)
start_block = 13617577
# end_block = w3.eth.blockNumber
end_block = 13827520

# to_address='0x7a58c0be72be218b41c608b7fe7c5bb630736c71'
to_address = '0xd569D3CCE55b71a8a3f3C418c329A66e5f714431'
# Juicebox: Terminal V1
# 0xd569d3cce55b71a8a3f3c418c329a66e5f714431
# MethodID: 0x02c8986f
# [0]:  0000000000000000000000000000000000000000000000000000000000000024
# transcatio=w3.eth.get_transaction('0x0f46b60e81fe0015a19f053d0e4f3db6cbdb0e99ca91c7fa9d784d5b94166b1e')
# print(transcatio)
# 0xa9059cbb
# curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":67}' http://localhost:8555
# 0x095ea7b3 approve


def convert_decimal(dict_item):
    # This function iterates a dictionary looking for types of Decimal and converts them to Decimal128
    # Embedded dictionaries and lists are called recursively.
    if dict_item is None:
        return None

    for k, v in list(dict_item.items()):
        if isinstance(v, dict):
            convert_decimal(v)
        elif isinstance(v, list):
            for l in v:
                convert_decimal(l)
        elif isinstance(v, Decimal):
            dict_item[k] = Decimal128(str(v))

    return dict_item


addresslist = []


def collect():
    for block_num in range(start_block, end_block):
        print("block_num", block_num)
        current_block = block_num
        # Get block with specific number with all transactions
        block = w3.eth.getBlock(block_num, full_transactions=True)
        list_of_block_transactions = block.transactions
        for transaction in list_of_block_transactions:
            to_account = transaction['to']
            from_account = transaction['from']
            # print(to_account)
            if to_account == to_address:
                print("To account:", to_account)
                to_match = True
            else:
                to_match = False
            # indexes= [i for i,x in enumerate(addresslist) if x['address'] == from_account]
            # # indexes = [index for index in range(len(a)) if a[index] == 'bar']
            # if len(indexes)>=1:
            #     print(indexes)
            if to_match == True:
                if transaction.input[:74] == '0x02c8986f0000000000000000000000000000000000000000000000000000000000000024':
                    # print("Transaction HASH:", transaction['hash'].hex())
                    # print("Transaction value:", Web3.fromWei(transaction['value'], 'ether'))
                    # print("Transaction Address:", from_account)
                    # print("Balance:", Web3.fromWei( w3.eth.get_balance(from_account), 'ether'))
                    try:
                        object = {
                            "address": from_account,
                            "balance": Web3.fromWei(w3.eth.get_balance(from_account), 'ether'),
                            "value": Web3.fromWei(transaction['value'], 'ether'),
                            "hash": transaction['hash'].hex(),
                            "location": "PEOPLE"
                        }
                        object = convert_decimal(object)
                        db.addresses.insert_one(object)
                    except Exception:
                        pass
                    # addresslist.append(object)


# print(addresslist)

# tx = '0x5c7e74a21419a6ff825aca9b54df1a86599b4b1ee82e60e6410e8d54cbb58b2c'
# w3.eth.getTransactionReceipt(tx).logs
# web3.eth.filter({
#     'fromBlock': 1000000,
#     'toBlock': 1000100,
#     'address': '0x6C8f2A135f6ed072DE4503Bd7C4999a1a17F824B'
#     })
# myContract = web3.eth.contract(address=contract_address, abi=contract_abi)
# tx_hash = myContract.functions.myFunction().transact()
# receipt = web3.eth.getTransactionReceipt(tx_hash)
# logs = myContract.events.myEvent().processReceipt(receipt)
# nonce = web3.eth.getTransactionCount(account_1)

# tx = {
#     'nonce': nonce,
#     'to': account_2,
#     'value': web3.toWei(1, 'ether'),
#     'gas': 2000000,
#     'gasPrice': web3.toWei('50', 'gwei')
# }

# #sign the transaction
# signed_tx = web3.eth.account.sign_transaction(tx, private_key1)

# #send transaction
# tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)

# #get transaction hash
# print(web3.toHex(tx_hash))
# balanceWEI = web3.fromWei(balance, "ether")
